//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package org_dao

import (
	"context"
	"fmt"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"atomgit.com/openlinksaas/proto-gen-go.git/org_member_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type MemberPermInfoDbItem struct {
	ManageDepartMentPerm     bool `bson:"manageDepartMentPerm"`
	ManageAssetCate          bool `bson:"manageAssetCate"`
	ManageAllAsset           bool `bson:"manageAllAsset"`
	ManageDepartMentAsset    bool `bson:"manageDepartMentAsset"`
	ManageSelfAsset          bool `bson:"manageSelfAsset"`
	ManageEvaluateTarget     bool `bson:"manageEvaluateTarget"`
	ViewAllEvaluate          bool `bson:"viewAllEvaluate"`
	ManageDepartMentEvaluate bool `bson:"manageDepartMentEvaluate"`
}

type MemberInfoDbItem struct {
	MemberId           string               `bson:"_id"`
	OrgId              string               `bson:"orgId"`
	MemberUserId       string               `bson:"memberUserId"`
	ParentDepartMentId string               `bson:"parentDepartMentId"`
	CreateTime         int64                `bson:"createTime"`
	MemberPermInfo     MemberPermInfoDbItem `bson:"memberPermInfo"`
}

func (item *MemberInfoDbItem) ToMemberInfo() *org_member_api.MemberInfo {
	return &org_member_api.MemberInfo{
		OrgId:              item.OrgId,
		MemberUserId:       item.MemberUserId,
		ParentDepartMentId: item.ParentDepartMentId,
		CreateTime:         item.CreateTime,
		MemberPermInfo: &org_member_api.MemberPermInfo{
			ManageDepartMentPerm:     item.MemberPermInfo.ManageDepartMentPerm,
			ManageAssetCate:          item.MemberPermInfo.ManageAssetCate,
			ManageAllAsset:           item.MemberPermInfo.ManageAllAsset,
			ManageDepartMentAsset:    item.MemberPermInfo.ManageDepartMentAsset,
			ManageSelfAsset:          item.MemberPermInfo.ManageSelfAsset,
			ManageEvaluateTarget:     item.MemberPermInfo.ManageEvaluateTarget,
			ViewAllEvaluate:          item.MemberPermInfo.ViewAllEvaluate,
			ManageDepartMentEvaluate: item.MemberPermInfo.ManageDepartMentEvaluate,
		},
	}
}

type _MemberDao struct {
	mc *mongo.Collection
}

func newMemberDao(db *mongo.Database) (*_MemberDao, error) {
	mc := db.Collection(db_ns.DB_NS_ORG + "member")
	_, err := mc.Indexes().CreateMany(context.Background(), []mongo.IndexModel{
		{
			Keys: bson.D{{"orgId", 1}, {"parentDepartMentId", 1}},
		},
		{
			Keys: bson.D{{"memberUserId", 1}},
		},
	})
	if err != nil {
		return nil, err
	}
	return &_MemberDao{mc: mc}, nil
}

func (db *_MemberDao) Insert(ctx context.Context, dbItem *MemberInfoDbItem) error {
	dbItem.MemberId = db.genMemberId(dbItem.OrgId, dbItem.MemberUserId)
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_MemberDao) genMemberId(orgId, memberUserId string) string {
	return fmt.Sprintf("%s:%s", orgId, memberUserId)
}

func (db *_MemberDao) Get(ctx context.Context, orgId, memberUserId string) (*MemberInfoDbItem, error) {
	memberId := db.genMemberId(orgId, memberUserId)
	retItem := &MemberInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": memberId, "orgId": orgId}).Decode(retItem)
	return retItem, err
}

func (db *_MemberDao) Exist(ctx context.Context, orgId, memberUserId string) (bool, error) {
	memberId := db.genMemberId(orgId, memberUserId)
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": memberId, "orgId": orgId})
	return count > 0, err
}

func (db *_MemberDao) Remove(ctx context.Context, orgId, memberUserId string) error {
	memberId := db.genMemberId(orgId, memberUserId)
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": memberId, "orgId": orgId})
	return err
}

func (db *_MemberDao) RemoveByOrg(ctx context.Context, orgId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"orgId": orgId})
	return err
}

func (db *_MemberDao) CountByDepartment(ctx context.Context, orgId, parentDepartMentId string) (uint32, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"orgId": orgId, "parentDepartMentId": parentDepartMentId})
	return uint32(count), err
}

func (db *_MemberDao) CountById(ctx context.Context, orgId, parentDepartMentId string, memberUserIdList []string) (uint32, error) {
	if len(memberUserIdList) == 0 {
		return 0, nil
	}
	memberIdList := []string{}
	for _, memberUserId := range memberUserIdList {
		memberIdList = append(memberIdList, db.genMemberId(orgId, memberUserId))
	}
	count, err := db.mc.CountDocuments(ctx, bson.M{"orgId": orgId, "parentDepartMentId": parentDepartMentId, "_id": bson.M{"$in": memberIdList}})
	return uint32(count), err
}

func (db *_MemberDao) CountByOrg(ctx context.Context, orgId string) (uint32, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"orgId": orgId})
	return uint32(count), err
}

func (db *_MemberDao) UpdateDepartment(ctx context.Context, orgId, memberUserId, parentDepartMentId string) error {
	memberId := db.genMemberId(orgId, memberUserId)
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": memberId, "orgId": orgId}, bson.M{"$set": bson.M{"parentDepartMentId": parentDepartMentId}})
	return err
}

func (db *_MemberDao) UpdateMemberPerm(ctx context.Context, orgId, memberUserId string, dbItem *MemberPermInfoDbItem) error {
	memberId := db.genMemberId(orgId, memberUserId)
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": memberId, "orgId": orgId}, bson.M{"$set": bson.M{"memberPermInfo": dbItem}})
	return err
}

func (db *_MemberDao) ListByOrg(ctx context.Context, orgId string) ([]*MemberInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"orgId": orgId}, options.Find().SetSort(bson.M{"createTime": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*MemberInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_MemberDao) ListByDepartMent(ctx context.Context, orgId, parentDepartMentId string) ([]*MemberInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"orgId": orgId, "parentDepartMentId": parentDepartMentId}, options.Find().SetSort(bson.M{"createTime": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*MemberInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_MemberDao) DistinctByUser(ctx context.Context, memberUserId string) ([]string, error) {
	tmpItemList, err := db.mc.Distinct(ctx, "orgId", bson.M{"memberUserId": memberUserId})
	if err != nil {
		return nil, err
	}

	retList := []string{}
	for _, tmpItem := range tmpItemList {
		retList = append(retList, tmpItem.(string))
	}
	return retList, nil
}
